// 游戏状态
const gameState = {
    currentGame: null,
    minesweeper: {
        grid: [],
        mines: 10,
        size: 8,
        gameOver: false
    },
    pixelArt: {
        selectedColor: '#000000'
    },
    snake: {
        snake: [{x: 7, y: 7}],
        food: {x: 5, y: 5},
        direction: 'right',
        gameOver: false,
        score: 0,
        interval: null
    }
};

// DOM 元素
const gameElements = {
    container: document.getElementById('game-container'),
    minesweeperBtn: document.getElementById('minesweeper'),
    pixelArtBtn: document.getElementById('pixel-art'),
    snakeBtn: document.getElementById('snake')
};

// 扫雷游戏
function initMinesweeper() {
    const { size, mines } = gameState.minesweeper;
    gameState.minesweeper.grid = [];
    gameState.minesweeper.gameOver = false;
    
    // 创建空网格
    for (let y = 0; y < size; y++) {
        const row = [];
        for (let x = 0; x < size; x++) {
            row.push({
                isMine: false,
                isRevealed: false,
                isFlagged: false,
                adjacentMines: 0
            });
        }
        gameState.minesweeper.grid.push(row);
    }
    
    // 随机放置地雷
    let minesPlaced = 0;
    while (minesPlaced < mines) {
        const x = Math.floor(Math.random() * size);
        const y = Math.floor(Math.random() * size);
        
        if (!gameState.minesweeper.grid[y][x].isMine) {
            gameState.minesweeper.grid[y][x].isMine = true;
            minesPlaced++;
            
            // 更新周围格子的地雷计数
            for (let dy = -1; dy <= 1; dy++) {
                for (let dx = -1; dx <= 1; dx++) {
                    const ny = y + dy;
                    const nx = x + dx;
                    
                    if (ny >= 0 && ny < size && nx >= 0 && nx < size) {
                        gameState.minesweeper.grid[ny][nx].adjacentMines++;
                    }
                }
            }
        }
    }
    
    // 创建UI
    const gridElement = document.createElement('div');
    gridElement.className = 'minesweeper-grid';
    
    for (let y = 0; y < size; y++) {
        for (let x = 0; x < size; x++) {
            const cell = document.createElement('div');
            cell.className = 'minesweeper-cell';
            cell.dataset.x = x;
            cell.dataset.y = y;
            
            cell.addEventListener('click', () => revealCell(x, y));
            cell.addEventListener('contextmenu', (e) => {
                e.preventDefault();
                flagCell(x, y);
            });
            
            gridElement.appendChild(cell);
        }
    }
    
    gameElements.container.innerHTML = '';
    gameElements.container.appendChild(gridElement);
}

// 揭示扫雷格子
function revealCell(x, y) {
    const { grid, gameOver } = gameState.minesweeper;
    if (gameOver || grid[y][x].isRevealed || grid[y][x].isFlagged) return;
    
    grid[y][x].isRevealed = true;
    
    const cell = document.querySelector(`.minesweeper-cell[data-x="${x}"][data-y="${y}"]`);
    cell.classList.add('revealed');
    
    if (grid[y][x].isMine) {
        cell.textContent = '💣';
        endMinesweeperGame(false);
        return;
    }
    
    if (grid[y][x].adjacentMines > 0) {
        cell.textContent = grid[y][x].adjacentMines;
        
        // 根据数字设置颜色
        const colors = ['blue', 'green', 'red', 'purple', 'maroon', 'turquoise', 'black', 'gray'];
        cell.style.color = colors[grid[y][x].adjacentMines - 1] || 'black';
    } else {
        // 如果是空格子，自动揭示周围的格子
        const { size } = gameState.minesweeper;
        for (let dy = -1; dy <= 1; dy++) {
            for (let dx = -1; dx <= 1; dx++) {
                const ny = y + dy;
                const nx = x + dx;
                
                if (ny >= 0 && ny < size && nx >= 0 && nx < size && !grid[ny][nx].isRevealed) {
                    revealCell(nx, ny);
                }
            }
        }
    }
    
    // 检查是否胜利
    checkMinesweeperWin();
}

// 标记扫雷格子
function flagCell(x, y) {
    const { grid, gameOver } = gameState.minesweeper;
    if (gameOver || grid[y][x].isRevealed) return;
    
    grid[y][x].isFlagged = !grid[y][x].isFlagged;
    
    const cell = document.querySelector(`.minesweeper-cell[data-x="${x}"][data-y="${y}"]`);
    cell.classList.toggle('flagged');
}

// 检查扫雷胜利
function checkMinesweeperWin() {
    const { grid, size, mines } = gameState.minesweeper;
    let revealedCount = 0;
    
    for (let y = 0; y < size; y++) {
        for (let x = 0; x < size; x++) {
            if (grid[y][x].isRevealed) revealedCount++;
        }
    }
    
    if (revealedCount === size * size - mines) {
        endMinesweeperGame(true);
    }
}

// 结束扫雷游戏
function endMinesweeperGame(isWin) {
    gameState.minesweeper.gameOver = true;
    
    if (isWin) {
        showAchievementPopup('扫雷高手', '成功完成一局扫雷游戏');
        alert('恭喜你赢了！');
    } else {
        alert('游戏结束！');
    }
    
    // 揭示所有地雷
    const { grid, size } = gameState.minesweeper;
    for (let y = 0; y < size; y++) {
        for (let x = 0; x < size; x++) {
            if (grid[y][x].isMine && !grid[y][x].isRevealed) {
                const cell = document.querySelector(`.minesweeper-cell[data-x="${x}"][data-y="${y}"]`);
                cell.classList.add('revealed');
                cell.textContent = '💣';
            }
        }
    }
}

// 像素画游戏
function initPixelArt() {
    const colors = [
        '#000000', '#ffffff', '#ff0000', '#00ff00', '#0000ff', 
        '#ffff00', '#ff00ff', '#00ffff', '#ff9900', '#9900ff'
    ];
    
    const container = document.createElement('div');
    container.style.display = 'flex';
    container.style.flexDirection = 'column';
    container.style.alignItems = 'center';
    
    // 颜色选择器
    const palette = document.createElement('div');
    palette.className = 'color-palette';
    
    colors.forEach(color => {
        const colorOption = document.createElement('div');
        colorOption.className = 'color-option';
        colorOption.style.backgroundColor = color;
        if (color === gameState.pixelArt.selectedColor) {
            colorOption.classList.add('selected');
        }
        
        colorOption.addEventListener('click', () => {
            document.querySelectorAll('.color-option').forEach(opt => opt.classList.remove('selected'));
            colorOption.classList.add('selected');
            gameState.pixelArt.selectedColor = color;
        });
        
        palette.appendChild(colorOption);
    });
    
    // 像素网格
    const grid = document.createElement('div');
    grid.className = 'pixel-art-grid';
    
    for (let i = 0; i < 16 * 16; i++) {
        const pixel = document.createElement('div');
        pixel.className = 'pixel';
        
        pixel.addEventListener('click', () => {
            pixel.style.backgroundColor = gameState.pixelArt.selectedColor;
        });
        
        // 支持拖动绘制
        pixel.addEventListener('mousedown', () => {
            window.isDrawing = true;
            pixel.style.backgroundColor = gameState.pixelArt.selectedColor;
        });
        
        pixel.addEventListener('mouseover', () => {
            if (window.isDrawing) {
                pixel.style.backgroundColor = gameState.pixelArt.selectedColor;
            }
        });
        
        grid.appendChild(pixel);
    }
    
    // 清除按钮
    const clearBtn = document.createElement('button');
    clearBtn.textContent = '清除画布';
    clearBtn.style.marginTop = '10px';
    clearBtn.addEventListener('click', () => {
        document.querySelectorAll('.pixel').forEach(p => p.style.backgroundColor = 'white');
    });
    
    container.appendChild(palette);
    container.appendChild(grid);
    container.appendChild(clearBtn);
    
    gameElements.container.innerHTML = '';
    gameElements.container.appendChild(container);
    
    // 停止绘制
    document.addEventListener('mouseup', () => {
        window.isDrawing = false;
    });
}

// 初始化贪吃蛇游戏
function initSnakeGame() {
    // 重置游戏状态
    gameState.snake = {
        snake: [{x: 7, y: 7}],
        food: {x: 5, y: 5},
        direction: 'right',
        gameOver: false,
        score: 0,
        interval: null
    };
    
    // 创建游戏容器
    const container = document.createElement('div');
    container.className = 'snake-game';
    
    // 创建游戏面板
    const board = document.createElement('div');
    board.className = 'snake-board';
    
    // 创建网格
    for (let y = 0; y < 15; y++) {
        for (let x = 0; x < 15; x++) {
            const cell = document.createElement('div');
            cell.className = 'snake-cell';
            cell.dataset.x = x;
            cell.dataset.y = y;
            board.appendChild(cell);
        }
    }
    
    // 分数显示
    const score = document.createElement('div');
    score.className = 'snake-score';
    score.textContent = '分数: 0';
    
    // 控制按钮
    const controls = document.createElement('div');
    controls.className = 'snake-controls';
    
    const startBtn = document.createElement('button');
    startBtn.textContent = '开始';
    startBtn.addEventListener('click', startSnakeGame);
    
    const resetBtn = document.createElement('button');
    resetBtn.textContent = '重置';
    resetBtn.addEventListener('click', pauseSnakeGame);
    
    controls.appendChild(startBtn);
    controls.appendChild(resetBtn);
    
    container.appendChild(board);
    container.appendChild(score);
    container.appendChild(controls);
    
    gameElements.container.innerHTML = '';
    gameElements.container.appendChild(container);
    
    // 键盘控制
    document.addEventListener('keydown', handleSnakeKeyPress);
    
    // 放置初始食物
    placeSnakeFood();
    updateSnakeBoard();
}

// 开始贪吃蛇游戏
function startSnakeGame() {
    if (gameState.snake.interval) {
        clearInterval(gameState.snake.interval);
        gameState.snake.interval = null;
        document.querySelector('.snake-controls button:first-child').textContent = '继续';
        return;
    }
    
    document.querySelector('.snake-controls button:first-child').textContent = '暂停';
    gameState.snake.gameOver = false;
    gameState.snake.interval = setInterval(() => {
        moveSnake();
        updateSnakeBoard();
        
        if (gameState.snake.gameOver) {
            clearInterval(gameState.snake.interval);
            gameState.snake.interval = null;
            document.querySelector('.snake-controls button:first-child').textContent = '重新开始';
            alert(`游戏结束！你的分数: ${gameState.snake.score}`);
            
            // 检查成就
            if (gameState.snake.score >= 5) {
                showAchievementPopup('贪吃蛇新手', '在贪吃蛇游戏中获得5分以上');
            }
            if (gameState.snake.score >= 10) {
                showAchievementPopup('贪吃蛇高手', '在贪吃蛇游戏中获得10分以上');
            }
        }
    }, 200);
}

// 暂停贪吃蛇游戏
function pauseSnakeGame() {
    // 重置游戏
    clearInterval(gameState.snake.interval);
    gameState.snake.interval = null;
    gameState.snake = {
        snake: [{x: 7, y: 7}],
        food: {x: 5, y: 5},
        direction: 'right',
        gameOver: false,
        score: 0,
        interval: null
    };
    document.querySelector('.snake-score').textContent = `分数: 0`;
    document.querySelector('.snake-controls button:first-child').textContent = '开始';
    updateSnakeBoard();
}

// 处理贪吃蛇键盘输入
function handleSnakeKeyPress(e) {
    const { direction } = gameState.snake;
    
    switch (e.key) {
        case 'ArrowUp':
            if (direction !== 'down') gameState.snake.direction = 'up';
            break;
        case 'ArrowDown':
            if (direction !== 'up') gameState.snake.direction = 'down';
            break;
        case 'ArrowLeft':
            if (direction !== 'right') gameState.snake.direction = 'left';
            break;
        case 'ArrowRight':
            if (direction !== 'left') gameState.snake.direction = 'right';
            break;
    }
}

// 移动贪吃蛇
function moveSnake() {
    const { snake, direction, food } = gameState.snake;
    const head = {...snake[0]};
    
    // 根据方向移动
    switch (direction) {
        case 'up': head.y--; break;
        case 'down': head.y++; break;
        case 'left': head.x--; break;
        case 'right': head.x++; break;
    }
    
    // 检查是否撞墙
    if (head.x < 0 || head.x >= 15 || head.y < 0 || head.y >= 15) {
        gameState.snake.gameOver = true;
        return;
    }
    
    // 检查是否撞到自己
    for (const segment of snake) {
        if (segment.x === head.x && segment.y === head.y) {
            gameState.snake.gameOver = true;
            return;
        }
    }
    
    // 添加新的头部
    snake.unshift(head);
    
    // 检查是否吃到食物
    if (head.x === food.x && head.y === food.y) {
        gameState.snake.score++;
        document.querySelector('.snake-score').textContent = `分数: ${gameState.snake.score}`;
        placeSnakeFood();
    } else {
        // 如果没吃到食物，移除尾部
        snake.pop();
    }
}

// 放置贪吃蛇食物
function placeSnakeFood() {
    const { snake } = gameState.snake;
    let x, y;
    let validPosition = false;
    
    while (!validPosition) {
        x = Math.floor(Math.random() * 15);
        y = Math.floor(Math.random() * 15);
        validPosition = true;
        
        // 确保食物不会出现在蛇身上
        for (const segment of snake) {
            if (segment.x === x && segment.y === y) {
                validPosition = false;
                break;
            }
        }
    }
    
    gameState.snake.food = { x, y };
}

// 更新贪吃蛇游戏面板
function updateSnakeBoard() {
    const { snake, food } = gameState.snake;
    
    // 清除所有单元格
    document.querySelectorAll('.snake-cell').forEach(cell => {
        cell.classList.remove('snake', 'food');
    });
    
    // 绘制蛇
    snake.forEach(segment => {
        const cell = document.querySelector(`.snake-cell[data-x="${segment.x}"][data-y="${segment.y}"]`);
        if (cell) {
            cell.classList.add('snake');
        }
    });
    
    // 绘制食物
    const foodCell = document.querySelector(`.snake-cell[data-x="${food.x}"][data-y="${food.y}"]`);
    if (foodCell) {
        foodCell.classList.add('food');
    }
}

// 初始化游戏选项
function initGames() {
    // 扫雷游戏
    gameElements.minesweeperBtn.addEventListener('click', () => {
        gameState.currentGame = 'minesweeper';
        initMinesweeper();
    });
    
    // 像素画游戏
    gameElements.pixelArtBtn.addEventListener('click', () => {
        gameState.currentGame = 'pixelArt';
        initPixelArt();
    });
    
    // 贪吃蛇游戏
    gameElements.snakeBtn.addEventListener('click', () => {
        gameState.currentGame = 'snake';
        initSnakeGame();
    });
    
    // 切换内容标签页
    const tabBtns = document.querySelectorAll('.tab-btn');
    const tabPanels = document.querySelectorAll('.tab-panel');
    
    tabBtns.forEach(btn => {
        btn.addEventListener('click', () => {
            const tabId = btn.dataset.tab;
            
            // 激活按钮
            tabBtns.forEach(b => b.classList.remove('active'));
            btn.classList.add('active');
            
            // 显示内容
            tabPanels.forEach(panel => panel.classList.remove('active'));
            document.getElementById(`${tabId}-tab`).classList.add('active');
        });
    });
    
    // 加载更多冷知识
    document.getElementById('more-facts').addEventListener('click', loadMoreFacts);
    
    // 冥想按钮
    document.getElementById('meditation-btn').addEventListener('click', startMeditation);
    
    // 伸展运动按钮
    document.getElementById('stretch-btn').addEventListener('click', showStretchExercises);
}

// 加载更多冷知识
function loadMoreFacts() {
    const facts = [
        "一只章鱼有三颗心脏，两颗用来将血液泵到鳃中，一颗将血液泵到身体其他部位。",
        "蜜蜂可以辨别出特定的人脸，并记住它们。",
        "打印机上的喷墨墨水比香水还贵。",
        "香蕉在黑光下会发蓝色荧光。",
        "每两分钟，我们拍摄的照片比19世纪存在的所有照片还要多。",
        "人类大脑每天产生的电量足以点亮一个小灯泡。",
        "国际空间站以每秒7.66公里的速度环绕地球运行。",
        "一个人的DNA，如果展开，可以延伸到太阳系之外。",
        "玻璃在技术上是一种液体，只是流动极其缓慢。",
        "地球上的黄金大部分来自陨石撞击。"
    ];
    
    const randomFact = facts[Math.floor(Math.random() * facts.length)];
    const articlesTab = document.getElementById('articles-tab');
    
    const newArticle = document.createElement('div');
    newArticle.className = 'article';
    
    const title = document.createElement('h4');
    title.textContent = '又一个冷知识';
    
    const content = document.createElement('p');
    content.textContent = randomFact;
    
    newArticle.appendChild(title);
    newArticle.appendChild(content);
    
    // 插入到按钮之前
    articlesTab.insertBefore(newArticle, document.getElementById('more-facts'));
    
    // 如果加载了3次以上的冷知识，解锁成就
    const articleCount = document.querySelectorAll('#articles-tab .article').length;
    if (articleCount >= 5) {
        showAchievementPopup('知识渊博', '阅读了5个冷知识');
    }
}

// 开始冥想
function startMeditation() {
    const relaxTab = document.getElementById('relax-tab');
    const meditationBtn = document.getElementById('meditation-btn');
    
    // 创建或更新冥想计时器
    let meditationTimer = document.getElementById('meditation-timer');
    
    if (!meditationTimer) {
        meditationTimer = document.createElement('div');
        meditationTimer.id = 'meditation-timer';
        meditationTimer.style.marginTop = '10px';
        meditationTimer.style.textAlign = 'center';
        meditationTimer.style.fontSize = '1.2rem';
        
        // 插入到冥想选项之后
        document.querySelector('.relax-option').appendChild(meditationTimer);
    }
    
    // 设置60秒的冥想时间
    let seconds = 60;
    meditationTimer.textContent = `剩余时间: ${seconds}秒`;
    meditationBtn.disabled = true;
    meditationBtn.textContent = '冥想中...';
    
    // 播放冥想背景音乐（在实际项目中可以添加）
    // const audio = new Audio('sounds/meditation.mp3');
    // audio.loop = true;
    // audio.play();
    
    const interval = setInterval(() => {
        seconds--;
        meditationTimer.textContent = `剩余时间: ${seconds}秒`;
        
        if (seconds <= 0) {
            clearInterval(interval);
            meditationBtn.disabled = false;
            meditationBtn.textContent = '开始';
            meditationTimer.textContent = '冥想完成!';
            // audio.pause();
            
            showAchievementPopup('内心平静', '完成了一次冥想');
        }
    }, 1000);
}

// 显示伸展运动
function showStretchExercises() {
    const exercises = [
        "颈部拉伸：慢慢将头向右倾斜，感受左侧颈部的拉伸，保持5秒。然后向左倾斜，重复。",
        "肩部放松：抬起肩膀向耳朵方向，保持3秒，然后放松。重复5次。",
        "手腕旋转：旋转手腕做圆周运动，每个方向各5次。",
        "背部伸展：双手高举过头，十指交叉向上伸展，同时深呼吸。",
        "眼睛休息：用掌心轻轻覆盖眼睛，让眼睛在黑暗中放松30秒。"
    ];
    
    const stretchContainer = document.createElement('div');
    stretchContainer.style.marginTop = '10px';
    stretchContainer.style.backgroundColor = '#f5f5f5';
    stretchContainer.style.padding = '10px';
    stretchContainer.style.borderRadius = '5px';
    
    const title = document.createElement('h5');
    title.textContent = '办公室伸展运动:';
    title.style.marginBottom = '10px';
    
    const list = document.createElement('ol');
    list.style.paddingLeft = '20px';
    
    exercises.forEach(exercise => {
        const item = document.createElement('li');
        item.textContent = exercise;
        item.style.marginBottom = '5px';
        list.appendChild(item);
    });
    
    stretchContainer.appendChild(title);
    stretchContainer.appendChild(list);
    
    // 添加一个计时器
    const timer = document.createElement('div');
    timer.textContent = '每个动作坚持 30 秒';
    timer.style.marginTop = '10px';
    timer.style.fontWeight = 'bold';
    timer.style.textAlign = 'center';
    
    stretchContainer.appendChild(timer);
    
    // 替换原有内容
    const stretchOption = document.getElementById('stretch-btn').parentNode;
    stretchOption.innerHTML = '';
    stretchOption.appendChild(document.createElement('h4')).textContent = '伸展运动';
    stretchOption.appendChild(stretchContainer);
    
    showAchievementPopup('健康达人', '查看了伸展运动指南');
}

// 当页面加载完成后初始化游戏
document.addEventListener('DOMContentLoaded', initGames);
